package com.hstc.servlet;

import com.hstc.common.Const;
import com.hstc.dao.DraftDAO;
import com.hstc.db.DbFactory;
import com.hstc.dto.MessageDTO;
import com.hstc.pojo.Draft;
import com.hstc.pojo.Users;
import com.hstc.util.SMTPHelp;
import com.hstc.util.UploadUtil;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Connection;
import java.util.*;

@WebServlet(name = "DraftServlet")
public class DraftServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String url = request.getRequestURI();
        String basePath = "/jsp/";
        Users user = (Users) request.getSession().getAttribute(Const.USERNAME);
        if(url.toUpperCase().indexOf("DRAFTLIST") != -1){

            Connection connection = DbFactory.getConnection();
            DraftDAO draftDAO = new DraftDAO();
            Draft draft = new Draft();
            draft.setUsername(user.getUsername());
            List<Draft> draftList = draftDAO.getDraftList(draft, connection);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("draftList", draftList);
            response.getWriter().write(jsonObject.toString());

        }else if(url.toUpperCase().indexOf("SAVEDRAFT") != -1) {

            //保存为草稿箱
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //2、创建一个文件上传解析器
            ServletFileUpload upload = new ServletFileUpload(factory);
            Map map = new HashMap();
            List<FileItem> list = null;
            String filename=null;
            try {
                list = upload.parseRequest(request);
            } catch (FileUploadException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            for(FileItem item : list) {
                //如果fileitem中封装的是普通输入项的数据
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString("UTF-8");
                    map.put(name, value);
                } else {//如果fileitem中封装的是上传文件

                    InputStream stream = item.getInputStream();//上传文件需要的文件流参数
                    filename = item.getName();   //上传文件需要的参数
                    if(filename == null || filename.trim().equals("")) {
                        continue;
                    }
                    UploadUtil.uploadFile(stream, Const.FILESAVEPATH, filename);   //调用工具类方法

                }
            }

            //保存邮件
            try {
                Session session = SMTPHelp.createSession();
                Message msg = new MimeMessage(session);
                InternetAddress from = new InternetAddress();
                from.setPersonal(user.getUsername());
                from.setAddress(SMTPHelp.getFrom(user.getUsername()));
                msg.setFrom(from);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String)map.get("toList")));
                msg.setSentDate(new Date());
                msg.setSubject((String)map.get("subject"));

                //抄送和暗送的处理
                msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse((String)map.get("ccList")));
                msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse((String)map.get("bccList")));
                MimeMultipart allMultipart = new MimeMultipart("mixed");
                //判断是否filename是否为空，添加附件的操作，
                if (filename != null && !filename.trim().equals("")) {

                    // TODO判空处理
                    MimeBodyPart attachPart1 = SMTPHelp.createAttachment(Const.FILESAVEPATH + filename);
                    //创建用于组合邮件正文和附件的MimeMultipart对象。
                    allMultipart.addBodyPart(attachPart1);
                }

                MimeBodyPart htmlBodyPart = SMTPHelp.createHtmlContent((String)map.get("content"));
                allMultipart.addBodyPart(htmlBodyPart);
                msg.setContent(allMultipart);
                msg.saveChanges();
                String draftFileName = UUID.randomUUID().toString() + ".eml";
                // 邮件对象
                File file = new File(Const.FILESAVEPATH + draftFileName);
                // 获得输出流
                OutputStream ips = new FileOutputStream(file);
                // 把邮件内容写入到文件
                msg.writeTo(ips);
                // 关闭流
                ips.close();
                DraftDAO draftDAO = new DraftDAO();
                Draft draft = new Draft(draftFileName);
                Connection connection = DbFactory.getConnection();
                if(draftDAO.addUser(draft, connection )){
                    request.setAttribute("msg", "存为草稿成功");
                }else{
                    request.setAttribute("msg", "存为草稿失败");
                }
            }catch (MessagingException e) {
                e.printStackTrace();
                request.setAttribute("msg", "存为草稿失败");
            }catch (Exception e1) {
                e1.printStackTrace();
                request.setAttribute("msg", "存为草稿失败");
            }
            url = basePath + "sendEmail.jsp";
            request.getRequestDispatcher(url).forward(request, response);


        }else if(url.toUpperCase().indexOf("KILLDRAFT") != -1) {
            //删除邮件

            String  checkedIdArrayString = request.getParameter("checkedIdArray");
            String [] checkedIdArray = checkedIdArrayString.split(",");
            Integer [] checkedIdArray2 = new Integer[checkedIdArray.length];
            DraftDAO draftDAO = new DraftDAO();
            boolean check = false;
            boolean check1 = false;
            for(int i = 0; i < checkedIdArray.length; i++) {
                checkedIdArray2[i] = Integer.parseInt(checkedIdArray[i]);
                String fileName = draftDAO.getFileName(checkedIdArray2[i], DbFactory.getConnection());
                File file = new File(Const.FILESAVEPATH + fileName);
               check =  file.delete();
                check1 = draftDAO.killDraft(checkedIdArray2[i], DbFactory.getConnection());
                if(!check || !check1) {
                    break;
                }
            }
            if(!check || !check1){
                response.getWriter().write("删除失败");
            }else {
                response.getWriter().write("成功删除");
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
    }
}
